﻿//生成[PostCategory]Service代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FineAdmin.IService;
using FineAdmin.Model;
using FineAdmin.IRepository;
using FineAdmin.Common;

namespace FineAdmin.Service
{
    public class PostCategoryService : BaseService<PostCategoryModel>, IPostCategoryService
    {
        public IPostCategoryRepository PostCategoryRepository { get; set; }
        public IEnumerable<PostCategoryModel> GetPostCategoryList()
        {
            return PostCategoryRepository.GetPostCategoryList();
        }


        public dynamic GetListByFilter(PostCategoryModel filter, PageInfo pageInfo)
        {
            string _where = " where 1=1";
            return GetListByFilter(filter, pageInfo, _where);
        }


        /// <summary>
        /// Items treeSelect数据列表
        /// </summary>
        public IEnumerable<TreeSelect> GetTreeSelect()
        {
            IEnumerable<PostCategoryModel> moduleList = PostCategoryRepository.GetAll("Id,Name,Pid", "ORDER BY SortCode ASC");
            var rootModuleList = moduleList.Where(x => x.Pid == 0).OrderBy(x => x.SortCode);
            List<TreeSelect> treeSelectList = new List<TreeSelect>();
            foreach (var item in rootModuleList)
            {
                TreeSelect tree = new TreeSelect
                {
                    id = item.Id,
                    name = item.Name,
                    open = false
                };
                GetChildren(treeSelectList, moduleList, tree, item.Id);
                treeSelectList.Add(tree);
            }
            return treeSelectList;
        }

        /// <summary>
        /// 递归遍历treeSelectList
        /// </summary>
        private void GetChildren(List<TreeSelect> treeSelectList, IEnumerable<PostCategoryModel> moduleList, TreeSelect tree, int id)
        {
            var childModuleList = moduleList.Where(x => x.Pid == id).OrderBy(x => x.SortCode);
            if (childModuleList != null && childModuleList.Count() > 0)
            {
                List<TreeSelect> _children = new List<TreeSelect>();
                foreach (var item in childModuleList)
                {
                    TreeSelect _tree = new TreeSelect
                    {
                        id = item.Id,
                        name = item.Name,
                        open = false
                    };
                    _children.Add(_tree);
                    tree.children = _children;
                    GetChildren(treeSelectList, moduleList, _tree, item.Id);
                }
            }
        }

    }

}